import type { DataSource, DataSourceResponse } from "@/types/dataSource";
import type { ApiConfig, ApiResponse } from "@/types/api";
import { DataSourceStatus, DataSourceType } from "@/types/dataSource";
import { ApiMethod, ApiStatus, ApiType } from "@/types/api";

// Mock 数据源列表
const mockDataSources: DataSource[] = [
  {
    id: 1,
    name: "主数据库",
    type: DataSourceType.MySQL,
    host: "localhost",
    port: 3306,
    username: "root",
    password: "******",
    database: "main_db",
    status: DataSourceStatus.Connected,
    createdAt: "2024-03-21 12:00:00",
    updatedAt: "2024-03-21 12:00:00",
  },
  {
    id: 2,
    name: "Redis缓存",
    type: DataSourceType.Redis,
    host: "redis.example.com",
    port: 6379,
    username: "admin",
    password: "******",
    database: "0",
    status: DataSourceStatus.Connected,
    createdAt: "2024-03-21 12:00:00",
    updatedAt: "2024-03-21 12:00:00",
  },
];

// Mock API列表
const mockApis: ApiConfig[] = [
  {
    id: 1,
    name: "获取用户信息",
    path: "/api/users/:id",
    method: ApiMethod.GET,
    type: ApiType.DataSource,
    status: ApiStatus.Enabled,
    description: "获取当前登录用户的详细信息",
    dataSourceId: 1,
    config: {
      sql: "SELECT * FROM users WHERE id = :userId",
      params: {
        userId: { type: "number" },
      },
    },
    requestSchema: JSON.stringify(
      {
        type: "object",
        properties: {
          userId: { type: "number" },
        },
        required: ["userId"],
      },
      null,
      2
    ),
    responseSchema: JSON.stringify(
      {
        type: "object",
        properties: {
          id: { type: "number" },
          username: { type: "string" },
          email: { type: "string" },
        },
      },
      null,
      2
    ),
    createdAt: "2024-03-21 12:00:00",
    updatedAt: "2024-03-21 12:00:00",
  },
  {
    id: 2,
    name: "天气查询",
    path: "/api/weather",
    method: ApiMethod.GET,
    type: ApiType.REST,
    status: ApiStatus.Enabled,
    description: "获取指定城市的天气信息",
    config: {
      url: "https://api.weather.com/v1/weather",
      method: ApiMethod.GET,
      headers: {
        "Content-Type": "application/json",
        "Api-Key": "your-api-key",
      },
      params: {
        city: { type: "string" },
      },
    },
    requestSchema: JSON.stringify(
      {
        type: "object",
        properties: {
          city: { type: "string" },
        },
        required: ["city"],
      },
      null,
      2
    ),
    responseSchema: JSON.stringify(
      {
        type: "object",
        properties: {
          temperature: { type: "number" },
          humidity: { type: "number" },
          description: { type: "string" },
        },
      },
      null,
      2
    ),
    createdAt: "2024-03-21 12:00:00",
    updatedAt: "2024-03-21 12:00:00",
  },
];

// Mock 延迟函数
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

// Mock API 响应
export const mockApi = {
  // 数据源相关接口
  async getDataSourceList(params: {
    keyword?: string;
    page: number;
    pageSize: number;
  }): Promise<DataSourceResponse> {
    await delay(500);
    let list = [...mockDataSources];

    if (params.keyword) {
      list = list.filter(
        (item) =>
          item.name.toLowerCase().includes(params.keyword!.toLowerCase()) ||
          item.host.toLowerCase().includes(params.keyword!.toLowerCase())
      );
    }

    const start = (params.page - 1) * params.pageSize;
    const end = start + params.pageSize;

    return {
      list: list.slice(start, end),
      total: list.length,
    };
  },

  async createDataSource(data: Omit<DataSource, "id">): Promise<DataSource> {
    await delay(500);
    const newDataSource: DataSource = {
      ...data,
      id: Math.max(...mockDataSources.map((ds) => ds.id ?? 0)) + 1,
      status: DataSourceStatus.Connected,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    mockDataSources.push(newDataSource);
    return newDataSource;
  },

  async updateDataSource(
    id: number,
    data: Partial<DataSource>
  ): Promise<DataSource> {
    await delay(500);
    const index = mockDataSources.findIndex((ds) => ds.id === id);
    if (index === -1) {
      throw new Error("数据源不存在");
    }
    mockDataSources[index] = {
      ...mockDataSources[index],
      ...data,
      updatedAt: new Date().toISOString(),
    };
    return mockDataSources[index];
  },

  async deleteDataSource(id: number): Promise<void> {
    await delay(500);
    const index = mockDataSources.findIndex((ds) => ds.id === id);
    if (index === -1) {
      throw new Error("数据源不存在");
    }
    mockDataSources.splice(index, 1);
  },

  async testDataSourceConnection(
    id: number
  ): Promise<{ success: boolean; message: string }> {
    await delay(1000);
    const dataSource = mockDataSources.find((ds) => ds.id === id);
    if (!dataSource) {
      return { success: false, message: "数据源不存在" };
    }
    return { success: true, message: "连接成功" };
  },

  // API相关接口
  async getApiList(params: ApiQuery): Promise<ApiResponse> {
    await delay(500);
    let list = [...mockApis];

    if (params.keyword) {
      const keyword = params.keyword.toLowerCase();
      list = list.filter(
        (api) =>
          api.name.toLowerCase().includes(keyword) ||
          api.path.toLowerCase().includes(keyword)
      );
    }

    const start = (params.page - 1) * params.pageSize;
    const end = start + params.pageSize;
    return {
      list: list.slice(start, end),
      total: list.length,
    };
  },

  async createApi(data: Omit<ApiConfig, "id">): Promise<ApiConfig> {
    await delay(500);
    const newApi: ApiConfig = {
      ...data,
      id: Math.max(...mockApis.map((api) => api.id ?? 0)) + 1,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    mockApis.push(newApi);
    return newApi;
  },

  async updateApi(id: number, data: Partial<ApiConfig>): Promise<ApiConfig> {
    await delay(500);
    const index = mockApis.findIndex((api) => api.id === id);
    if (index === -1) {
      throw new Error("API不存在");
    }
    mockApis[index] = {
      ...mockApis[index],
      ...data,
      updatedAt: new Date().toISOString(),
    };
    return mockApis[index];
  },

  async deleteApi(id: number): Promise<void> {
    await delay(500);
    const index = mockApis.findIndex((api) => api.id === id);
    if (index === -1) {
      throw new Error("API不存在");
    }
    mockApis.splice(index, 1);
  },

  async testApi(
    id: number
  ): Promise<{ success: boolean; message: string; data?: any }> {
    await delay(1000);
    const api = mockApis.find((api) => api.id === id);
    if (!api) {
      return { success: false, message: "API不存在" };
    }

    // 模拟测试结果
    if (api.type === ApiType.DataSource) {
      return {
        success: true,
        message: "SQL执行成功",
        data: {
          sql: (api.config as SqlConfig).sql,
          params: (api.config as SqlConfig).params,
        },
      };
    } else {
      return {
        success: true,
        message: "REST接口调用成功",
        data: {
          url: (api.config as RestConfig).url,
          method: (api.config as RestConfig).method,
        },
      };
    }
  },
};
